<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="top">
        <view class="basic">
          <view class="basic_img">
            <image :src="$data.info._picurl" />
          </view>
          <view class="basic_content">
            <view class="basic_content--title">
              {{ $data.info.serviceTitle }}
            </view>
            <view class="basic_content--price text-price">
              {{ $data.info.firstTotalPrice }}
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 保障 </view>
          <view class="row_right">
            <view class="flex align-center flex-warp">
              <view
                class="margin-right"
                v-for="(item, index) of $data.info.serviceSnapshot
                  .serviceTagNameArr"
                :key="index"
              >
                <up-icon
                  name="checkmark-circle"
                  color="#111111"
                  labelColor="#111111"
                  :label="item"
                  :size="18"
                  :labelSize="16"
                ></up-icon>
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 温馨提示 </view>
          <view class="row_right">
            {{ removeHtmlTags($data.info.serviceSnapshot.tips) }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单总价 </view>
          <view class="row_right text-price">{{ $data.info.totalPrice }}</view>
        </view>
        <view class="row">
          <view class="row_left"> 优惠 </view>
          <view class="row_right text-price">
            -{{ $data.info.couponPrice }}
          </view>
        </view>
        <!-- <view class="row" v-if="$data.info.fast">
          <view class="row_left"> 加急 </view>
          <view class="row_right text-price">
            {{ $data.info.fast }}
          </view>
        </view> -->
        <view class="row">
          <view class="row_left"> 实付金额 </view>
          <view class="row_right">
            <text class="text-price row_right--price">
              {{ $data.info.firstTotalPrice }}
            </text>
          </view>
        </view>
      </view>
      <!-- 阿姨信息 -->
      <view class="worker" v-if="$data.info.workerDetail">
        <view class="detail">
          <view class="detail_img">
            <image :src="$data.info.workerDetail._avatar" />
          </view>
          <view class="detail_content">
            <view class="detail_content--title">
              {{ $data.info.workerDetail.nickname }}
            </view>
            <view class="scoring">
              <view
                class="scoring_item"
                v-for="(icon, iconIndex) in 5"
                :key="iconIndex"
              >
                <up-icon
                  name="star-fill"
                  :color="
                    iconIndex < $data.info.workerDetail.star
                      ? BasicConfig.MainColor
                      : '#bbbbbb'
                  "
                ></up-icon>
              </view>
            </view>
            <view class="detail_content--phone">
              <view>
                {{ hidePhone($data.info.workerDetail.phone) }}
              </view>
              <view class="copy" @tap="onCall(phoneType.worker)">
                联系保洁师
              </view>
            </view>
          </view>
        </view>
        <!-- 首次上门完工照 -->
        <view class="padding" v-if="$data.info._firstFinalImgList.length > 0">
          <view class="margin-tb">完工照</view>
          <view class="text-gray">
            {{ $data.info.orderServiceWorker.completedAt }}
          </view>
          <view class="imgs">
            <view
              class="img"
              v-for="(item, index) of $data.info._firstFinalImgList"
              :key="index"
              @tap="previewImage(item, index, $data.info._firstFinalImgList)"
            >
              <image :src="item" />
            </view>
          </view>
        </view>
        <!-- 二次上门完工照 -->
        <view class="padding" v-if="$data.info._secondFinalImgList.length > 0">
          <view class="margin-tb">二次上门完工照</view>
          <view class="text-gray">
            {{ $data.info.secondOrderServiceWorker.completedAt }}
          </view>
          <view class="imgs">
            <view
              class="img"
              v-for="(item, index) of $data.info._secondFinalImgList"
              :key="index"
              @tap="previewImage(item, index, $data.info._secondFinalImgList)"
            >
              <image :src="item" />
            </view>
          </view>
        </view>
        <view class="second" v-if="$data.seconShow">
          <view class="btn btn_cancel" @tap="onSecond(2)">拒绝上门</view>
          <view class="btn btn_save" @tap="onSecond(1)">同意上门</view>
        </view>
      </view>

      <view class="margin-top padding-lr bg-white">
        <view class="row">
          <view class="row_left"> 服务时间 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>{{ $data.info._firstStartServicedAt }}</view>
              <view class="copy text-nowarp" @tap="onCall(phoneType.custom)">
                修改
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 服务地址 </view>
          <view class="row_right">
            {{ $data.info.addressSnapshot.locationAddress }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 联系人 </view>
          <view class="row_right">
            <text> {{ $data.info.addressSnapshot.name }}</text>
            <text>
              ({{ $data.info.addressSnapshot.sex == 1 ? "先生" : "女士" }})
            </text>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单编号 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>
                {{ $data.info.localNo }}
              </view>
              <view class="copy text-nowarp" @tap="onCopy($data.info.localNo)">
                复制
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 下单时间 </view>
          <view class="row_right">
            {{ $data.info._createdAt }}
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="foot foot_box" v-if="$data.btnShow">
        <block v-if="isDown">
          <view class="btn btn_down">服务已下架</view>
        </block>
        <block v-else>
          <view class="btn btn_cancel" @tap="onComplaint"> 投诉 </view>

          <block
            v-if="$data.info && $data.info.dyGoodsType == goodsType.reservation"
          >
            <view
              class="btn btn_save"
              v-if="
                $data.info.refundSwitch == reservaSwitch.off &&
                $data.info.status != orderStatus.awaitReservation
              "
              @tap="onCall(phoneType.custom)"
            >
              联系客服
            </view>
            <view class="btn btn_save" v-else @tap="onApply"> 申请售后 </view>
          </block>
          <view class="btn btn_cancel" v-else @tap="onCall(phoneType.custom)">
            申请售后
          </view>
          <view class="btn btn_save" @tap="onConfirm"> 确认服务 </view>
        </block>
      </view>
    </view>
    <PopupCSPhone
      v-model:show="$data.csphoneShow"
      :title="$data.csTitle"
      :type="$data.csType"
      :phone="phone"
    />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import {
  getOrderDetail,
  operationSecondService,
  receiptOrder,
} from "../../../../api/Interface/order";
import errorCode from "../../../../utils/http/errorCode";
import { isDev } from "../../../../utils/env";
import BasicConfig from "../../../../utils/config";
import {
  orderSecondStatus,
  orderSourceType,
  orderStatus,
  orderStatusConfig,
  orderType,
  searchOrderStatus,
} from "../../../../enums/order";
import { jumpPage } from "../../../../utils/route/route";
import PopupCSPhone from "../../../../components/PopupCSPhone.vue";
import { phoneType } from "../../../../enums/common";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import "dayjs/locale/zh-cn";
import { useImgSrc } from "../../../../hooks/useImg";
import { usePayment } from "../../../../hooks/usePay";
import { hidePhone, removeHtmlTags } from "../../../../utils/utils";
import { goodsType, reservaSwitch } from "../../../../enums/goods";
import { usePageBack } from "../../../../hooks/useCommon";
import { useJumpOrderPage } from "../../../../hooks/useOrder";
dayjs.extend(duration);
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: null,
  csphoneShow: false,
  csTitle: "联系电话",
  csType: phoneType.custom,
  /**
   * 首次firstStatus===5,二次secondStatus===1 =>显示 二次上门"拒绝上门"or"同意上门"
   */
  seconShow: false,
  /**
   * 底部按钮组
   *  首次firstStatus===5,二次secondStatus===1 =>显示 二次上门"拒绝上门"or"同意上门" 选择后 才显示最下方按钮组
   */
  btnShow: false,
});
// 二次服务
const onSecond = async (type) => {
  const { code, data, msg } = await operationSecondService({
    localNo: $data.localNo,
    type,
  });
  BasicConfig.toast(msg);
  if (code === errorCode.success) {
    // 同意二次上门
    if (type === 1) {
      const { isNeedPay, localNo: secondLocalNo } = data;
      // 需要支付
      if (isNeedPay == 1) {
        console.log("二次上门需要支付");
        await usePayment({
          localNo: secondLocalNo,
          type: orderSourceType.second,
        }).then((res) => {
          console.log("二次上门支付", res);
          if (res.code === errorCode.success) {
            console.log("二次上门支付成功");
            // console.log("二次上门支付成功后将要跳转");
            // init();
            jumpPage({
              to: "/package-service/pages/order/details/awaitService",
              mode: "redirectTo",
              query: {
                localNo: secondLocalNo,
                orderServiceId: $data.orderServiceId,
              },
            });
          } else {
            BasicConfig.toast(res.msg);
            console.log("二次上门支付未成功");
          }
        });
      } else {
        console.log("二次上门不需要支付");
        // setTimeout(() => {
        console.log("二次上门不需要支付,即将跳转");
        jumpPage({
          to: "/package-service/pages/order/details/awaitService",
          mode: "redirectTo",
          query: {
            localNo: secondLocalNo,
            orderServiceId: $data.orderServiceId,
          },
        });
        // }, 1000);
      }
    }
    // 拒绝二次上门
    else {
      init();
    }
  }
};
const _onSecond = async (type) => {
  operationSecondService({
    localNo: $data.localNo,
    type,
  }).then((res) => {
    BasicConfig.toast(res.msg);
    if (res.code === errorCode.success) {
      setTimeout(() => {
        // 同意二次上门
        if (type === 1) {
          const { isNeedPay, localNo: secondLocalNo } = res.data;
          // 需要支付
          if (isNeedPay == 1) {
            usePayment({
              localNo: secondLocalNo,
              type: orderSourceType.second,
            }).then((res) => {
              BasicConfig.toast(res.msg);
            });
          }
          uni.navigateBack({
            delta: 1,
          });
        }
        // 拒绝二次上门
        else {
          init();
        }
      }, 1000);
    }
  });
};
const onCopy = (text) => {
  uni.setClipboardData({
    data: text.toString(),
    success: (result) => {
      BasicConfig.toast("复制成功");
    },
    fail: (error) => {
      console.log("复制失败", error);
      BasicConfig.toast("复制失败!");
    },
  });
};
const init = () => {
  getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      useJumpOrderPage(res.data);
      if ($data.info) {
        setTitle();
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info._firstFinalImgList = [];
        $data.info._secondFinalImgList = [];
        // if (isDev) {
        //   $data.info.workerDetail = {
        //     //保洁详情
        //     nickname: "李*", //保洁姓名
        //     avatar: "/logo.png", //保洁头像
        //     phone: "187****4521", //保洁电话
        //     totalGoodEvaluate: "100", //百分比
        //     star: 4, //星级
        //   };
        //   $data.info.secondOrderServiceWorker = {
        //     workerId: 1,
        //     status: 4,
        //     completedImg:
        //       "/storage/manage/20241219/79dec87f679b25e033cdb92d5b8edd68.jpeg,/storage/manage/20241219/79dec87f679b25e033cdb92d5b8edd68.jpeg", //二次上门完工照
        //     completedAt: "2024-12-30 15:55:57",
        //   };
        // }
        const {
          firstStartServicedAt,
          createdAt,
          orderServiceWorker,
          secondOrderServiceWorker,
          workerDetail,
        } = $data.info;
        $data.info._firstStartServicedAt = dayjs(firstStartServicedAt)
          .locale("zh-cn")
          .format("YYYY-MM-DD dddd HH:mm");
        $data.info._createdAt = dayjs(createdAt)
          .locale("zh-cn")
          .format("YYYY-MM-DD dddd HH:mm");

        if ($data.info.workerDetail) {
          $data.info.workerDetail._avatar = useImgSrc(
            $data.info.workerDetail.avatar
          );
        }
        // 保洁师信息
        if (workerDetail) {
          $data.info.workerDetail._avatar = useImgSrc(
            $data.info.workerDetail.avatar
          );
        }
        // 首次服务信息
        if (orderServiceWorker) {
          const { completedImg } = orderServiceWorker;
          const imgs = completedImg ? completedImg.split(",") : [];
          $data.info._firstFinalImgList = imgs.map((m) => useImgSrc(m));
        }
        // 二次服务信息
        if (secondOrderServiceWorker) {
          const { completedImg } = secondOrderServiceWorker;
          const imgs = completedImg ? completedImg.split(",") : [];
          $data.info._secondFinalImgList = imgs.map((m) => useImgSrc(m));
        }
        $data.seconShow =
          $data.info.firstStatus == orderStatus.awaitConfirm &&
          $data.info.secondStatus == orderSecondStatus.awaitPay;
        $data.btnShow = !$data.seconShow;
      }
    }
  });
};
const setTitle = () => {
  uni.setNavigationBarTitle({
    title: orderStatusConfig[$data.info.firstStatus]?.label ?? "",
  });
};
const onCall = (type) => {
  $data.csphoneShow = true;
  $data.csType = type;
  if (type == phoneType.worker) {
    $data.csTitle = "保洁师电话";
  } else if (type === phoneType.custom) {
    $data.csTitle = "官方客服电话";
  }
};
const phone = computed(() => {
  if ($data.info && $data.info.workerDetail && $data.info.workerDetail.phone) {
    return $data.info.workerDetail.phone;
  }
  return "";
});
/** 是否下架 domesticServiceStatus 0.已下架 1.已上架 */
const isDown = computed(() => {
  const { domesticServiceStatus } = $data.info;
  return domesticServiceStatus == 0;
});
/** 预览图片 */
const previewImage = (item, index, list) => {
  uni.previewImage({
    current: index,
    urls: list,
  });
};
const onConfirm = () => {
  console.log("$data.localNo", $data.localNo);
  uni.showModal({
    content: "确认服务?",
    success: (success) => {
      if (success.confirm) {
        receiptOrder({ localNo: $data.localNo }).then((res) => {
          BasicConfig.toast(res.msg);
          if (res.code === errorCode.success) {
            setTimeout(() => {
              // uni.navigateBack({
              //   delta: 1,
              // });
              usePageBack({
                delta: 1,
                url: "/package-service/pages/order/order",
                mode: "redirectTo",
                query: {
                  status: searchOrderStatus.awaitComment,
                },
              });
            }, 1000);
          }
        });
      }
    },
  });
};
const onComplaint = () => {
  jumpPage({
    to: "/package-service/pages/complain",
    query: {
      orderServiceId: $data.orderServiceId,
      domesticServiceId: $data.info.serviceSnapshot.domesticServiceId,
      localNo: $data.localNo,
      orderType: orderType.service,
    },
  });
};
const onApply = () => {
  // clearHandle();
  jumpPage({
    to: "/package-service/pages/order/afterSales/apply",
    query: {
      localNo: $data.localNo,
      orderServiceId: $data.orderServiceId,
    },
  });
};
onLoad((options) => {
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
  init();
});
onUnload(() => {});
onReady(() => {});
</script>

<style lang="scss" scoped>
@import "../../../static/style/order/detail/common.scss";
.worker {
  background: #ffffff;
  margin-top: 30rpx;
  .detail {
    padding: 30rpx;
    display: flex;
    align-items: center;
    &_img {
      width: 160rpx;
      height: 160rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 15rpx;
      }
    }
    .scoring {
      display: flex;
      align-items: center;
      margin: 20rpx 0;
    }
    &_content {
      width: calc(100% - 160rpx);
      padding-left: 30rpx;
      &--title {
        font-size: 38rpx;
        font-weight: 700;
      }
      &--phone {
        margin-top: 30rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  .second {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    .btn {
      flex: 1;
      border-radius: 100rpx;
      text-align: center;
      font-size: 32rpx;
      height: 90rpx;
      line-height: 90rpx;
      &:not(:first-child) {
        margin-left: 30rpx;
      }
    }
    .btn_save {
      background: $main-color;
      color: #ffffff;
    }
    .btn_cancel {
      border: 1px solid $main-color;
      color: $main-color;
      background: #ffffff;
    }
  }
}
.imgs {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 30rpx;
  .img {
    width: calc(94% / 4);
    height: 160rpx;
    &:not(:nth-of-type(4n)) {
      margin-right: 2%;
    }
    margin-bottom: 20rpx;
    image {
      width: 100%;
      height: 100%;
      border-radius: 20rpx;
    }
  }
}
</style>
